/**
 * 数据备份和恢复管理器
 * 提供数据备份、恢复、同步、版本管理等功能
 */

import { logInfo, logWarn, logError } from './errorHandler.js'
import { post, get, put } from './networkManager.js'
import { setCache, getCache, deleteCache } from './cacheManager.js'
import { setState, getState } from './stateManager.js'
import { getCurrentUser, isAuthenticated } from './authManager.js'
import { exportToJSON, importData } from './dataExport.js'

/**
 * 备份状态枚举
 */
export const BACKUP_STATUS = {
	IDLE: 'idle',
	BACKING_UP: 'backing_up',
	RESTORING: 'restoring',
	SYNCING: 'syncing',
	COMPLETED: 'completed',
	FAILED: 'failed',
	CANCELLED: 'cancelled'
}

/**
 * 备份类型枚举
 */
export const BACKUP_TYPES = {
	FULL: 'full',
	INCREMENTAL: 'incremental',
	DIFFERENTIAL: 'differential',
	SELECTIVE: 'selective',
	AUTO: 'auto',
	MANUAL: 'manual'
}

/**
 * 存储类型枚举
 */
export const STORAGE_TYPES = {
	LOCAL: 'local',
	CLOUD: 'cloud',
	BOTH: 'both'
}

/**
 * 数据类型枚举
 */
export const DATA_TYPES = {
	USER_DATA: 'user_data',
	GAME_PROGRESS: 'game_progress',
	SETTINGS: 'settings',
	ACHIEVEMENTS: 'achievements',
	STATISTICS: 'statistics',
	TEST_HISTORY: 'test_history',
	CUSTOM_THEMES: 'custom_themes',
	NOTIFICATIONS: 'notifications',
	CACHE_DATA: 'cache_data',
	ALL: 'all'
}

/**
 * 冲突解决策略枚举
 */
export const CONFLICT_RESOLUTION = {
	LOCAL_WINS: 'local_wins',
	REMOTE_WINS: 'remote_wins',
	MERGE: 'merge',
	MANUAL: 'manual',
	NEWEST_WINS: 'newest_wins',
	LARGEST_WINS: 'largest_wins'
}

/**
 * 备份项类
 */
class BackupItem {
	constructor(data = {}) {
		this.id = data.id || this.generateId()
		this.name = data.name || ''
		this.description = data.description || ''
		this.type = data.type || BACKUP_TYPES.MANUAL
		this.dataTypes = data.dataTypes || [DATA_TYPES.ALL]
		this.storageType = data.storageType || STORAGE_TYPES.LOCAL
		this.size = data.size || 0
		this.compressedSize = data.compressedSize || 0
		this.checksum = data.checksum || ''
		this.version = data.version || '1.0.0'
		this.appVersion = data.appVersion || ''
		this.deviceInfo = data.deviceInfo || {}
		this.userId = data.userId || null
		this.createdAt = data.createdAt || Date.now()
		this.updatedAt = data.updatedAt || Date.now()
		this.expiresAt = data.expiresAt || null
		this.status = data.status || BACKUP_STATUS.IDLE
		this.progress = data.progress || 0
		this.error = data.error || null
		this.metadata = data.metadata || {}
		this.tags = data.tags || []
		this.isEncrypted = data.isEncrypted || false
		this.isCompressed = data.isCompressed || true
		this.localPath = data.localPath || ''
		this.remotePath = data.remotePath || ''
		this.downloadUrl = data.downloadUrl || ''
		this.data = data.data || null
	}
	
	/**
	 * 生成备份ID
	 * @returns {string} 备份ID
	 */
	generateId() {
		return `backup_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
	}
	
	/**
	 * 检查备份是否有效
	 * @returns {boolean} 是否有效
	 */
	isValid() {
		return this.status === BACKUP_STATUS.COMPLETED && 
			   (!this.expiresAt || this.expiresAt > Date.now())
	}
	
	/**
	 * 检查备份是否过期
	 * @returns {boolean} 是否过期
	 */
	isExpired() {
		return this.expiresAt && this.expiresAt <= Date.now()
	}
	
	/**
	 * 获取备份大小（格式化）
	 * @returns {string} 格式化的大小
	 */
	getFormattedSize() {
		return this.formatBytes(this.size)
	}
	
	/**
	 * 获取压缩后大小（格式化）
	 * @returns {string} 格式化的压缩大小
	 */
	getFormattedCompressedSize() {
		return this.formatBytes(this.compressedSize)
	}
	
	/**
	 * 获取压缩率
	 * @returns {string} 压缩率百分比
	 */
	getCompressionRatio() {
		if (this.size === 0) return '0%'
		const ratio = ((this.size - this.compressedSize) / this.size * 100).toFixed(1)
		return `${ratio}%`
	}
	
	/**
	 * 格式化字节数
	 * @param {number} bytes - 字节数
	 * @returns {string} 格式化的大小
	 */
	formatBytes(bytes) {
		if (bytes === 0) return '0 B'
		const k = 1024
		const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
		const i = Math.floor(Math.log(bytes) / Math.log(k))
		return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
	}
	
	/**
	 * 更新备份信息
	 * @param {Object} data - 更新数据
	 */
	update(data) {
		Object.keys(data).forEach(key => {
			if (this.hasOwnProperty(key)) {
				this[key] = data[key]
			}
		})
		this.updatedAt = Date.now()
	}
	
	/**
	 * 转换为普通对象
	 * @param {boolean} includeData - 是否包含数据
	 * @returns {Object} 普通对象
	 */
	toObject(includeData = false) {
		const obj = {
			id: this.id,
			name: this.name,
			description: this.description,
			type: this.type,
			dataTypes: this.dataTypes,
			storageType: this.storageType,
			size: this.size,
			compressedSize: this.compressedSize,
			checksum: this.checksum,
			version: this.version,
			appVersion: this.appVersion,
			deviceInfo: this.deviceInfo,
			userId: this.userId,
			createdAt: this.createdAt,
			updatedAt: this.updatedAt,
			expiresAt: this.expiresAt,
			status: this.status,
			progress: this.progress,
			error: this.error,
			metadata: this.metadata,
			tags: this.tags,
			isEncrypted: this.isEncrypted,
			isCompressed: this.isCompressed,
			localPath: this.localPath,
			remotePath: this.remotePath,
			downloadUrl: this.downloadUrl
		}
		
		if (includeData) {
			obj.data = this.data
		}
		
		return obj
	}
}

/**
 * 备份管理器类
 */
class BackupManager {
	constructor() {
		// 备份列表
		this.backups = new Map()
		
		// 当前操作
		this.currentOperation = null
		
		// 配置选项
		this.config = {
			apiBaseUrl: '/api/backup',
			maxBackups: 10,
			maxBackupSize: 100 * 1024 * 1024, // 100MB
			autoBackupInterval: 24 * 60 * 60 * 1000, // 24小时
			backupRetention: 30 * 24 * 60 * 60 * 1000, // 30天
			enableCompression: true,
			enableEncryption: false,
			encryptionKey: '',
			defaultStorageType: STORAGE_TYPES.LOCAL,
			conflictResolution: CONFLICT_RESOLUTION.NEWEST_WINS,
			enableAutoBackup: true,
			backupOnAppClose: true,
			backupOnDataChange: false,
			verifyBackups: true,
			cleanupExpired: true,
			maxRetries: 3,
			retryDelay: 1000,
			timeout: 30000,
			chunkSize: 1024 * 1024, // 1MB
			progressCallback: null
		}
		
		// 事件监听器
		this.listeners = {
			backupStart: [],
			backupProgress: [],
			backupComplete: [],
			backupError: [],
			restoreStart: [],
			restoreProgress: [],
			restoreComplete: [],
			restoreError: [],
			syncStart: [],
			syncProgress: [],
			syncComplete: [],
			syncError: [],
			conflictDetected: []
		}
		
		// 自动备份定时器
		this.autoBackupTimer = null
		
		// 统计信息
		this.stats = {
			totalBackups: 0,
			successfulBackups: 0,
			failedBackups: 0,
			totalRestores: 0,
			successfulRestores: 0,
			failedRestores: 0,
			totalSyncs: 0,
			successfulSyncs: 0,
			failedSyncs: 0,
			totalDataSize: 0,
			totalCompressedSize: 0,
			lastBackupAt: null,
			lastRestoreAt: null,
			lastSyncAt: null,
			startTime: Date.now()
		}
		
		this.init()
	}
	
	/**
	 * 初始化备份管理器
	 */
	async init() {
		try {
			this.loadConfig()
			await this.loadBackups()
			this.setupAutoBackup()
			this.setupEventListeners()
			
			// 清理过期备份
			if (this.config.cleanupExpired) {
				await this.cleanupExpiredBackups()
			}
			
			logInfo('备份管理器已初始化', {
				backupCount: this.backups.size,
				autoBackupEnabled: this.config.enableAutoBackup
			})
		} catch (error) {
			logError('备份管理器初始化失败', { error: error.message })
		}
	}
	
	/**
	 * 加载配置
	 */
	loadConfig() {
		try {
			if (typeof uni !== 'undefined') {
				const saved = uni.getStorageSync('backup_config')
				if (saved) {
					this.config = { ...this.config, ...saved }
				}
			}
		} catch (error) {
			logError('加载备份配置失败', { error: error.message })
		}
	}
	
	/**
	 * 保存配置
	 */
	saveConfig() {
		try {
			if (typeof uni !== 'undefined') {
				uni.setStorageSync('backup_config', this.config)
			}
		} catch (error) {
			logError('保存备份配置失败', { error: error.message })
		}
	}
	
	/**
	 * 加载备份列表
	 */
	async loadBackups() {
		try {
			// 加载本地备份
			if (typeof uni !== 'undefined') {
				const localBackups = uni.getStorageSync('local_backups') || []
				localBackups.forEach(backupData => {
					const backup = new BackupItem(backupData)
					this.backups.set(backup.id, backup)
				})
			}
			
			// 加载云端备份（如果已登录）
			if (isAuthenticated()) {
				await this.loadCloudBackups()
			}
			
			// 更新统计信息
			this.updateStats()
		} catch (error) {
			logError('加载备份列表失败', { error: error.message })
		}
	}
	
	/**
	 * 加载云端备份
	 */
	async loadCloudBackups() {
		try {
			const response = await get(`${this.config.apiBaseUrl}/list`, {
				timeout: this.config.timeout
			})
			
			if (response.data.success) {
				response.data.backups.forEach(backupData => {
					const backup = new BackupItem(backupData)
					this.backups.set(backup.id, backup)
				})
			}
		} catch (error) {
			logWarn('加载云端备份失败', { error: error.message })
		}
	}
	
	/**
	 * 保存备份列表
	 */
	saveBackups() {
		try {
			if (typeof uni !== 'undefined') {
				const localBackups = Array.from(this.backups.values())
					.filter(backup => backup.storageType === STORAGE_TYPES.LOCAL || backup.storageType === STORAGE_TYPES.BOTH)
					.map(backup => backup.toObject())
				
				uni.setStorageSync('local_backups', localBackups)
			}
		} catch (error) {
			logError('保存备份列表失败', { error: error.message })
		}
	}
	
	/**
	 * 创建备份
	 * @param {Object} options - 备份选项
	 * @returns {Promise<BackupItem>} 备份项
	 */
	async createBackup(options = {}) {
		try {
			// 创建备份项
			const backup = new BackupItem({
				name: options.name || `备份_${new Date().toLocaleString()}`,
				description: options.description || '',
				type: options.type || BACKUP_TYPES.MANUAL,
				dataTypes: options.dataTypes || [DATA_TYPES.ALL],
				storageType: options.storageType || this.config.defaultStorageType,
				appVersion: this.getAppVersion(),
				deviceInfo: this.getDeviceInfo(),
				userId: isAuthenticated() ? getCurrentUser().id : null,
				expiresAt: options.expiresAt || (Date.now() + this.config.backupRetention),
				tags: options.tags || [],
				isEncrypted: options.isEncrypted || this.config.enableEncryption,
				isCompressed: options.isCompressed !== false && this.config.enableCompression
			})
			
			// 设置当前操作
			this.currentOperation = {
				type: 'backup',
				backupId: backup.id,
				startTime: Date.now(),
				cancelled: false
			}
			
			// 更新状态
			backup.status = BACKUP_STATUS.BACKING_UP
			this.backups.set(backup.id, backup)
			
			// 触发开始事件
			this.emit('backupStart', backup)
			
			// 收集数据
			const data = await this.collectData(backup.dataTypes, (progress) => {
				backup.progress = Math.floor(progress * 0.6) // 数据收集占60%
				this.emit('backupProgress', { backup, progress: backup.progress })
			})
			
			// 检查是否被取消
			if (this.currentOperation.cancelled) {
				backup.status = BACKUP_STATUS.CANCELLED
				throw new Error('备份已取消')
			}
			
			// 处理数据
			backup.data = data
			backup.size = this.calculateDataSize(data)
			
			// 压缩数据
			if (backup.isCompressed) {
				backup.progress = 60
				this.emit('backupProgress', { backup, progress: backup.progress })
				
				backup.data = await this.compressData(backup.data)
				backup.compressedSize = this.calculateDataSize(backup.data)
			} else {
				backup.compressedSize = backup.size
			}
			
			// 加密数据
			if (backup.isEncrypted) {
				backup.progress = 70
				this.emit('backupProgress', { backup, progress: backup.progress })
				
				backup.data = await this.encryptData(backup.data, this.config.encryptionKey)
			}
			
			// 生成校验和
			backup.checksum = await this.generateChecksum(backup.data)
			
			// 保存备份
			backup.progress = 80
			this.emit('backupProgress', { backup, progress: backup.progress })
			
			await this.saveBackupData(backup)
			
			// 完成备份
			backup.status = BACKUP_STATUS.COMPLETED
			backup.progress = 100
			backup.updatedAt = Date.now()
			
			// 保存备份信息
			this.backups.set(backup.id, backup)
			this.saveBackups()
			
			// 更新统计
			this.stats.totalBackups++
			this.stats.successfulBackups++
			this.stats.totalDataSize += backup.size
			this.stats.totalCompressedSize += backup.compressedSize
			this.stats.lastBackupAt = Date.now()
			
			// 清理当前操作
			this.currentOperation = null
			
			// 触发完成事件
			this.emit('backupComplete', backup)
			
			// 清理旧备份
			await this.cleanupOldBackups()
			
			logInfo('备份创建成功', {
				backupId: backup.id,
				name: backup.name,
				size: backup.getFormattedSize(),
				compressedSize: backup.getFormattedCompressedSize()
			})
			
			return backup
		} catch (error) {
			// 更新统计
			this.stats.totalBackups++
			this.stats.failedBackups++
			
			// 更新备份状态
			if (this.currentOperation && this.backups.has(this.currentOperation.backupId)) {
				const backup = this.backups.get(this.currentOperation.backupId)
				backup.status = BACKUP_STATUS.FAILED
				backup.error = error.message
				this.emit('backupError', { backup, error })
			}
			
			// 清理当前操作
			this.currentOperation = null
			
			logError('备份创建失败', { error: error.message })
			throw error
		}
	}
	
	/**
	 * 恢复备份
	 * @param {string} backupId - 备份ID
	 * @param {Object} options - 恢复选项
	 * @returns {Promise<boolean>} 是否成功
	 */
	async restoreBackup(backupId, options = {}) {
		try {
			const backup = this.backups.get(backupId)
			if (!backup) {
				throw new Error('备份不存在')
			}
			
			if (!backup.isValid()) {
				throw new Error('备份无效或已过期')
			}
			
			// 设置当前操作
			this.currentOperation = {
				type: 'restore',
				backupId: backup.id,
				startTime: Date.now(),
				cancelled: false
			}
			
			// 触发开始事件
			this.emit('restoreStart', backup)
			
			// 加载备份数据
			let data = await this.loadBackupData(backup)
			
			// 验证校验和
			if (this.config.verifyBackups) {
				const checksum = await this.generateChecksum(data)
				if (checksum !== backup.checksum) {
					throw new Error('备份数据校验失败')
				}
			}
			
			this.emit('restoreProgress', { backup, progress: 20 })
			
			// 解密数据
			if (backup.isEncrypted) {
				data = await this.decryptData(data, this.config.encryptionKey)
				this.emit('restoreProgress', { backup, progress: 40 })
			}
			
			// 解压数据
			if (backup.isCompressed) {
				data = await this.decompressData(data)
				this.emit('restoreProgress', { backup, progress: 60 })
			}
			
			// 检查是否被取消
			if (this.currentOperation.cancelled) {
				throw new Error('恢复已取消')
			}
			
			// 恢复数据
			await this.restoreData(data, options, (progress) => {
				const totalProgress = 60 + Math.floor(progress * 0.4) // 恢复占40%
				this.emit('restoreProgress', { backup, progress: totalProgress })
			})
			
			// 更新统计
			this.stats.totalRestores++
			this.stats.successfulRestores++
			this.stats.lastRestoreAt = Date.now()
			
			// 清理当前操作
			this.currentOperation = null
			
			// 触发完成事件
			this.emit('restoreComplete', backup)
			
			logInfo('备份恢复成功', {
				backupId: backup.id,
				name: backup.name
			})
			
			return true
		} catch (error) {
			// 更新统计
			this.stats.totalRestores++
			this.stats.failedRestores++
			
			// 清理当前操作
			this.currentOperation = null
			
			// 触发错误事件
			const backup = this.backups.get(backupId)
			this.emit('restoreError', { backup, error })
			
			logError('备份恢复失败', {
				backupId,
				error: error.message
			})
			
			throw error
		}
	}
	
	/**
	 * 同步备份
	 * @param {Object} options - 同步选项
	 * @returns {Promise<boolean>} 是否成功
	 */
	async syncBackups(options = {}) {
		try {
			if (!isAuthenticated()) {
				throw new Error('用户未登录，无法同步')
			}
			
			// 设置当前操作
			this.currentOperation = {
				type: 'sync',
				startTime: Date.now(),
				cancelled: false
			}
			
			// 触发开始事件
			this.emit('syncStart')
			
			// 获取本地和远程备份列表
			const localBackups = Array.from(this.backups.values())
				.filter(backup => backup.storageType === STORAGE_TYPES.LOCAL || backup.storageType === STORAGE_TYPES.BOTH)
			
			const remoteBackups = await this.getRemoteBackups()
			
			this.emit('syncProgress', { progress: 20 })
			
			// 检测冲突
			const conflicts = this.detectConflicts(localBackups, remoteBackups)
			
			if (conflicts.length > 0) {
				this.emit('conflictDetected', conflicts)
				
				// 根据策略解决冲突
				await this.resolveConflicts(conflicts, options.conflictResolution || this.config.conflictResolution)
			}
			
			this.emit('syncProgress', { progress: 50 })
			
			// 上传本地备份
			const toUpload = localBackups.filter(backup => 
				!remoteBackups.find(remote => remote.id === backup.id)
			)
			
			for (let i = 0; i < toUpload.length; i++) {
				if (this.currentOperation.cancelled) break
				
				await this.uploadBackup(toUpload[i])
				const progress = 50 + Math.floor((i + 1) / toUpload.length * 25)
				this.emit('syncProgress', { progress })
			}
			
			// 下载远程备份
			const toDownload = remoteBackups.filter(backup => 
				!localBackups.find(local => local.id === backup.id)
			)
			
			for (let i = 0; i < toDownload.length; i++) {
				if (this.currentOperation.cancelled) break
				
				await this.downloadBackup(toDownload[i])
				const progress = 75 + Math.floor((i + 1) / toDownload.length * 25)
				this.emit('syncProgress', { progress })
			}
			
			// 更新统计
			this.stats.totalSyncs++
			this.stats.successfulSyncs++
			this.stats.lastSyncAt = Date.now()
			
			// 清理当前操作
			this.currentOperation = null
			
			// 触发完成事件
			this.emit('syncComplete', {
				uploaded: toUpload.length,
				downloaded: toDownload.length,
				conflicts: conflicts.length
			})
			
			logInfo('备份同步成功', {
				uploaded: toUpload.length,
				downloaded: toDownload.length,
				conflicts: conflicts.length
			})
			
			return true
		} catch (error) {
			// 更新统计
			this.stats.totalSyncs++
			this.stats.failedSyncs++
			
			// 清理当前操作
			this.currentOperation = null
			
			// 触发错误事件
			this.emit('syncError', error)
			
			logError('备份同步失败', { error: error.message })
			throw error
		}
	}
	
	/**
	 * 收集数据
	 * @param {Array} dataTypes - 数据类型列表
	 * @param {Function} progressCallback - 进度回调
	 * @returns {Promise<Object>} 收集的数据
	 */
	async collectData(dataTypes, progressCallback) {
		const data = {}
		const totalTypes = dataTypes.length
		
		for (let i = 0; i < totalTypes; i++) {
			const dataType = dataTypes[i]
			const progress = (i / totalTypes) * 100
			
			if (progressCallback) {
				progressCallback(progress)
			}
			
			switch (dataType) {
				case DATA_TYPES.USER_DATA:
					data.userData = await this.collectUserData()
					break
				case DATA_TYPES.GAME_PROGRESS:
					data.gameProgress = await this.collectGameProgress()
					break
				case DATA_TYPES.SETTINGS:
					data.settings = await this.collectSettings()
					break
				case DATA_TYPES.ACHIEVEMENTS:
					data.achievements = await this.collectAchievements()
					break
				case DATA_TYPES.STATISTICS:
					data.statistics = await this.collectStatistics()
					break
				case DATA_TYPES.TEST_HISTORY:
					data.testHistory = await this.collectTestHistory()
					break
				case DATA_TYPES.CUSTOM_THEMES:
					data.customThemes = await this.collectCustomThemes()
					break
				case DATA_TYPES.NOTIFICATIONS:
					data.notifications = await this.collectNotifications()
					break
				case DATA_TYPES.CACHE_DATA:
					data.cacheData = await this.collectCacheData()
					break
				case DATA_TYPES.ALL:
					data.userData = await this.collectUserData()
					data.gameProgress = await this.collectGameProgress()
					data.settings = await this.collectSettings()
					data.achievements = await this.collectAchievements()
					data.statistics = await this.collectStatistics()
					data.testHistory = await this.collectTestHistory()
					data.customThemes = await this.collectCustomThemes()
					data.notifications = await this.collectNotifications()
					break
			}
		}
		
		if (progressCallback) {
			progressCallback(100)
		}
		
		return data
	}
	
	/**
	 * 收集用户数据
	 * @returns {Promise<Object>} 用户数据
	 */
	async collectUserData() {
		try {
			const userState = getState('user')
			return {
				userInfo: userState.userInfo,
				preferences: userState.preferences || {},
				profile: userState.profile || {}
			}
		} catch (error) {
			logWarn('收集用户数据失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集游戏进度
	 * @returns {Promise<Object>} 游戏进度
	 */
	async collectGameProgress() {
		try {
			const gameState = getState('game')
			return {
				currentLevel: gameState.currentLevel || 1,
				scores: gameState.scores || [],
				unlockedLevels: gameState.unlockedLevels || [],
				progress: gameState.progress || {}
			}
		} catch (error) {
			logWarn('收集游戏进度失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集设置
	 * @returns {Promise<Object>} 设置数据
	 */
	async collectSettings() {
		try {
			const settingsState = getState('settings')
			return {
				theme: settingsState.theme || 'light',
				language: settingsState.language || 'zh-CN',
				notifications: settingsState.notifications || {},
				audio: settingsState.audio || {},
				game: settingsState.game || {},
				privacy: settingsState.privacy || {}
			}
		} catch (error) {
			logWarn('收集设置失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集成就数据
	 * @returns {Promise<Object>} 成就数据
	 */
	async collectAchievements() {
		try {
			if (typeof uni !== 'undefined') {
				const achievements = uni.getStorageSync('achievements') || []
				return { achievements }
			}
			return {}
		} catch (error) {
			logWarn('收集成就数据失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集统计数据
	 * @returns {Promise<Object>} 统计数据
	 */
	async collectStatistics() {
		try {
			if (typeof uni !== 'undefined') {
				const statistics = uni.getStorageSync('statistics') || {}
				return { statistics }
			}
			return {}
		} catch (error) {
			logWarn('收集统计数据失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集测试历史
	 * @returns {Promise<Object>} 测试历史
	 */
	async collectTestHistory() {
		try {
			if (typeof uni !== 'undefined') {
				const testHistory = uni.getStorageSync('test_history') || []
				return { testHistory }
			}
			return {}
		} catch (error) {
			logWarn('收集测试历史失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集自定义主题
	 * @returns {Promise<Object>} 自定义主题
	 */
	async collectCustomThemes() {
		try {
			if (typeof uni !== 'undefined') {
				const customThemes = uni.getStorageSync('custom_themes') || []
				return { customThemes }
			}
			return {}
		} catch (error) {
			logWarn('收集自定义主题失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集通知数据
	 * @returns {Promise<Object>} 通知数据
	 */
	async collectNotifications() {
		try {
			if (typeof uni !== 'undefined') {
				const notifications = uni.getStorageSync('notifications') || []
				return { notifications }
			}
			return {}
		} catch (error) {
			logWarn('收集通知数据失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 收集缓存数据
	 * @returns {Promise<Object>} 缓存数据
	 */
	async collectCacheData() {
		try {
			// 只收集重要的缓存数据
			const importantCaches = ['user_profile', 'game_config', 'app_config']
			const cacheData = {}
			
			importantCaches.forEach(key => {
				const data = getCache(key)
				if (data) {
					cacheData[key] = data
				}
			})
			
			return { cacheData }
		} catch (error) {
			logWarn('收集缓存数据失败', { error: error.message })
			return {}
		}
	}
	
	/**
	 * 恢复数据
	 * @param {Object} data - 要恢复的数据
	 * @param {Object} options - 恢复选项
	 * @param {Function} progressCallback - 进度回调
	 * @returns {Promise<void>}
	 */
	async restoreData(data, options, progressCallback) {
		const dataKeys = Object.keys(data)
		const totalKeys = dataKeys.length
		
		for (let i = 0; i < totalKeys; i++) {
			const key = dataKeys[i]
			const progress = (i / totalKeys) * 100
			
			if (progressCallback) {
				progressCallback(progress)
			}
			
			switch (key) {
				case 'userData':
					await this.restoreUserData(data[key], options)
					break
				case 'gameProgress':
					await this.restoreGameProgress(data[key], options)
					break
				case 'settings':
					await this.restoreSettings(data[key], options)
					break
				case 'achievements':
					await this.restoreAchievements(data[key], options)
					break
				case 'statistics':
					await this.restoreStatistics(data[key], options)
					break
				case 'testHistory':
					await this.restoreTestHistory(data[key], options)
					break
				case 'customThemes':
					await this.restoreCustomThemes(data[key], options)
					break
				case 'notifications':
					await this.restoreNotifications(data[key], options)
					break
				case 'cacheData':
					await this.restoreCacheData(data[key], options)
					break
			}
		}
		
		if (progressCallback) {
			progressCallback(100)
		}
	}
	
	/**
	 * 恢复用户数据
	 * @param {Object} userData - 用户数据
	 * @param {Object} options - 选项
	 */
	async restoreUserData(userData, options) {
		try {
			if (options.overwrite !== false) {
				setState('user', userData)
			}
		} catch (error) {
			logWarn('恢复用户数据失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复游戏进度
	 * @param {Object} gameProgress - 游戏进度
	 * @param {Object} options - 选项
	 */
	async restoreGameProgress(gameProgress, options) {
		try {
			if (options.overwrite !== false) {
				setState('game', gameProgress)
			}
		} catch (error) {
			logWarn('恢复游戏进度失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复设置
	 * @param {Object} settings - 设置数据
	 * @param {Object} options - 选项
	 */
	async restoreSettings(settings, options) {
		try {
			if (options.overwrite !== false) {
				setState('settings', settings)
			}
		} catch (error) {
			logWarn('恢复设置失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复成就数据
	 * @param {Object} achievementsData - 成就数据
	 * @param {Object} options - 选项
	 */
	async restoreAchievements(achievementsData, options) {
		try {
			if (typeof uni !== 'undefined' && options.overwrite !== false) {
				uni.setStorageSync('achievements', achievementsData.achievements || [])
			}
		} catch (error) {
			logWarn('恢复成就数据失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复统计数据
	 * @param {Object} statisticsData - 统计数据
	 * @param {Object} options - 选项
	 */
	async restoreStatistics(statisticsData, options) {
		try {
			if (typeof uni !== 'undefined' && options.overwrite !== false) {
				uni.setStorageSync('statistics', statisticsData.statistics || {})
			}
		} catch (error) {
			logWarn('恢复统计数据失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复测试历史
	 * @param {Object} testHistoryData - 测试历史
	 * @param {Object} options - 选项
	 */
	async restoreTestHistory(testHistoryData, options) {
		try {
			if (typeof uni !== 'undefined' && options.overwrite !== false) {
				uni.setStorageSync('test_history', testHistoryData.testHistory || [])
			}
		} catch (error) {
			logWarn('恢复测试历史失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复自定义主题
	 * @param {Object} themesData - 主题数据
	 * @param {Object} options - 选项
	 */
	async restoreCustomThemes(themesData, options) {
		try {
			if (typeof uni !== 'undefined' && options.overwrite !== false) {
				uni.setStorageSync('custom_themes', themesData.customThemes || [])
			}
		} catch (error) {
			logWarn('恢复自定义主题失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复通知数据
	 * @param {Object} notificationsData - 通知数据
	 * @param {Object} options - 选项
	 */
	async restoreNotifications(notificationsData, options) {
		try {
			if (typeof uni !== 'undefined' && options.overwrite !== false) {
				uni.setStorageSync('notifications', notificationsData.notifications || [])
			}
		} catch (error) {
			logWarn('恢复通知数据失败', { error: error.message })
		}
	}
	
	/**
	 * 恢复缓存数据
	 * @param {Object} cacheData - 缓存数据
	 * @param {Object} options - 选项
	 */
	async restoreCacheData(cacheData, options) {
		try {
			if (options.overwrite !== false) {
				Object.keys(cacheData.cacheData || {}).forEach(key => {
					setCache(key, cacheData.cacheData[key])
				})
			}
		} catch (error) {
			logWarn('恢复缓存数据失败', { error: error.message })
		}
	}
	
	/**
	 * 压缩数据
	 * @param {Object} data - 要压缩的数据
	 * @returns {Promise<string>} 压缩后的数据
	 */
	async compressData(data) {
		try {
			// 简单的JSON压缩（实际项目中可以使用更高效的压缩算法）
			const jsonString = JSON.stringify(data)
			
			// 使用LZ压缩算法的简化版本
			return this.lzCompress(jsonString)
		} catch (error) {
			logWarn('数据压缩失败', { error: error.message })
			return JSON.stringify(data)
		}
	}
	
	/**
	 * 解压数据
	 * @param {string} compressedData - 压缩的数据
	 * @returns {Promise<Object>} 解压后的数据
	 */
	async decompressData(compressedData) {
		try {
			// 解压数据
			const jsonString = this.lzDecompress(compressedData)
			return JSON.parse(jsonString)
		} catch (error) {
			logWarn('数据解压失败', { error: error.message })
			// 尝试直接解析（可能未压缩）
			try {
				return JSON.parse(compressedData)
			} catch {
				throw new Error('数据格式错误')
			}
		}
	}
	
	/**
	 * LZ压缩算法简化版
	 * @param {string} str - 要压缩的字符串
	 * @returns {string} 压缩后的字符串
	 */
	lzCompress(str) {
		if (!str) return str
		
		const dict = {}
		const data = str.split('')
		const result = []
		let dictSize = 256
		let w = ''
		
		for (let i = 0; i < data.length; i++) {
			const c = data[i]
			const wc = w + c
			
			if (dict[wc]) {
				w = wc
			} else {
				result.push(dict[w] || w.charCodeAt(0))
				dict[wc] = dictSize++
				w = c
			}
		}
		
		if (w) {
			result.push(dict[w] || w.charCodeAt(0))
		}
		
		return result.join(',')
	}
	
	/**
	 * LZ解压算法简化版
	 * @param {string} str - 要解压的字符串
	 * @returns {string} 解压后的字符串
	 */
	lzDecompress(str) {
		if (!str) return str
		
		const dict = {}
		const data = str.split(',').map(Number)
		const result = []
		let dictSize = 256
		let w = String.fromCharCode(data[0])
		
		result.push(w)
		
		for (let i = 1; i < data.length; i++) {
			const k = data[i]
			let entry
			
			if (dict[k]) {
				entry = dict[k]
			} else if (k === dictSize) {
				entry = w + w.charAt(0)
			} else {
				entry = String.fromCharCode(k)
			}
			
			result.push(entry)
			dict[dictSize++] = w + entry.charAt(0)
			w = entry
		}
		
		return result.join('')
	}
	
	/**
	 * 加密数据
	 * @param {string} data - 要加密的数据
	 * @param {string} key - 加密密钥
	 * @returns {Promise<string>} 加密后的数据
	 */
	async encryptData(data, key) {
		try {
			if (!key) {
				throw new Error('加密密钥不能为空')
			}
			
			// 简单的XOR加密（实际项目中应使用更安全的加密算法）
			return this.xorEncrypt(data, key)
		} catch (error) {
			logWarn('数据加密失败', { error: error.message })
			return data
		}
	}
	
	/**
	 * 解密数据
	 * @param {string} encryptedData - 加密的数据
	 * @param {string} key - 解密密钥
	 * @returns {Promise<string>} 解密后的数据
	 */
	async decryptData(encryptedData, key) {
		try {
			if (!key) {
				throw new Error('解密密钥不能为空')
			}
			
			// XOR解密
			return this.xorDecrypt(encryptedData, key)
		} catch (error) {
			logWarn('数据解密失败', { error: error.message })
			throw error
		}
	}
	
	/**
	 * XOR加密
	 * @param {string} data - 要加密的数据
	 * @param {string} key - 密钥
	 * @returns {string} 加密后的数据
	 */
	xorEncrypt(data, key) {
		let result = ''
		for (let i = 0; i < data.length; i++) {
			const charCode = data.charCodeAt(i) ^ key.charCodeAt(i % key.length)
			result += String.fromCharCode(charCode)
		}
		return btoa(result) // Base64编码
	}
	
	/**
	 * XOR解密
	 * @param {string} encryptedData - 加密的数据
	 * @param {string} key - 密钥
	 * @returns {string} 解密后的数据
	 */
	xorDecrypt(encryptedData, key) {
		const data = atob(encryptedData) // Base64解码
		let result = ''
		for (let i = 0; i < data.length; i++) {
			const charCode = data.charCodeAt(i) ^ key.charCodeAt(i % key.length)
			result += String.fromCharCode(charCode)
		}
		return result
	}
	
	/**
	 * 验证备份数据
	 * @param {Object} data - 要验证的数据
	 * @returns {Promise<boolean>} 验证结果
	 */
	async verifyBackupData(data) {
		try {
			if (!data || typeof data !== 'object') {
				return false
			}
			
			// 检查必要的字段
			const requiredFields = ['timestamp', 'version', 'data']
			for (const field of requiredFields) {
				if (!(field in data)) {
					return false
				}
			}
			
			// 检查时间戳格式
			if (!Number.isInteger(data.timestamp) || data.timestamp <= 0) {
				return false
			}
			
			// 检查版本格式
			if (typeof data.version !== 'string' || !data.version.trim()) {
				return false
			}
			
			// 检查数据完整性
			if (!data.data || typeof data.data !== 'object') {
				return false
			}
			
			return true
		} catch (error) {
			logWarn('验证备份数据失败', { error: error.message })
			return false
		}
	}
	
	/**
	 * 清理过期备份
	 * @returns {Promise<void>}
	 */
	async cleanupExpiredBackups() {
		try {
			const now = Date.now()
			const retentionPeriod = this.config.retention * 24 * 60 * 60 * 1000 // 转换为毫秒
			
			// 清理本地过期备份
			this.backups = this.backups.filter(backup => {
				const isExpired = (now - backup.timestamp) > retentionPeriod
				if (isExpired) {
					logInfo('清理过期备份', { backupId: backup.id, name: backup.name })
					this.stats.cleanupCount++
				}
				return !isExpired
			})
			
			// 限制备份数量
			if (this.backups.length > this.config.maxBackups) {
				const excessCount = this.backups.length - this.config.maxBackups
				// 删除最旧的备份
				this.backups.sort((a, b) => a.timestamp - b.timestamp)
				const removedBackups = this.backups.splice(0, excessCount)
				
				removedBackups.forEach(backup => {
					logInfo('清理多余备份', { backupId: backup.id, name: backup.name })
					this.stats.cleanupCount++
				})
			}
			
			// 保存更新后的备份列表
			await this.saveBackups()
			
			logInfo('备份清理完成', { 
				remainingBackups: this.backups.length,
				cleanupCount: this.stats.cleanupCount
			})
		} catch (error) {
			logError('清理过期备份失败', { error: error.message })
			throw error
		}
	}
	
	/**
	 * 获取备份统计信息
	 * @returns {Object} 统计信息
	 */
	getStats() {
		return {
			...this.stats,
			totalBackups: this.backups.length,
			totalSize: this.backups.reduce((sum, backup) => sum + backup.size, 0),
			oldestBackup: this.backups.length > 0 ? 
				Math.min(...this.backups.map(b => b.timestamp)) : null,
			newestBackup: this.backups.length > 0 ? 
				Math.max(...this.backups.map(b => b.timestamp)) : null
		}
	}
	
	/**
	 * 重置统计信息
	 * @returns {void}
	 */
	resetStats() {
		this.stats = {
			createdCount: 0,
			restoredCount: 0,
			syncCount: 0,
			conflictCount: 0,
			errorCount: 0,
			cleanupCount: 0,
			lastOperation: null,
			lastError: null
		}
		logInfo('备份统计信息已重置')
	}
	
	/**
	 * 更新配置
	 * @param {Object} newConfig - 新配置
	 * @returns {Promise<void>}
	 */
	async updateConfig(newConfig) {
		try {
			this.config = { ...this.config, ...newConfig }
			await this.saveConfig()
			
			// 如果自动备份设置发生变化，重新设置定时器
			if ('autoBackup' in newConfig || 'autoBackupInterval' in newConfig) {
				this.setupAutoBackup()
			}
			
			logInfo('备份配置已更新', { config: this.config })
		} catch (error) {
			logError('更新备份配置失败', { error: error.message })
			throw error
		}
	}
	
	/**
	 * 获取配置
	 * @returns {Object} 当前配置
	 */
	getConfig() {
		return { ...this.config }
	}
	
	/**
	 * 导出备份数据
	 * @param {string} backupId - 备份ID
	 * @param {string} format - 导出格式 (json|csv)
	 * @returns {Promise<string>} 导出的数据
	 */
	async exportBackup(backupId, format = 'json') {
		try {
			const backup = this.backups.find(b => b.id === backupId)
			if (!backup) {
				throw new Error('备份不存在')
			}
			
			const backupData = await this.getLocalBackupData(backupId)
			
			switch (format.toLowerCase()) {
				case 'json':
					return JSON.stringify(backupData, null, 2)
				case 'csv':
					return this.convertToCSV(backupData)
				default:
					throw new Error('不支持的导出格式')
			}
		} catch (error) {
			logError('导出备份失败', { error: error.message, backupId })
			throw error
		}
	}
	
	/**
	 * 转换为CSV格式
	 * @param {Object} data - 要转换的数据
	 * @returns {string} CSV格式的数据
	 */
	convertToCSV(data) {
		try {
			const rows = []
			const headers = ['类型', '键', '值']
			rows.push(headers.join(','))
			
			const flattenData = (obj, prefix = '') => {
				Object.keys(obj).forEach(key => {
					const fullKey = prefix ? `${prefix}.${key}` : key
					const value = obj[key]
					
					if (value && typeof value === 'object' && !Array.isArray(value)) {
						flattenData(value, fullKey)
					} else {
						const csvValue = Array.isArray(value) ? 
							JSON.stringify(value) : String(value)
						rows.push([prefix || '数据', fullKey, csvValue].join(','))
					}
				})
			}
			
			flattenData(data.data || data)
			return rows.join('\n')
		} catch (error) {
			logWarn('转换CSV格式失败', { error: error.message })
			return ''
		}
	}
	
	/**
	 * 导入备份数据
	 * @param {string} importData - 要导入的数据
	 * @param {string} format - 数据格式
	 * @param {Object} options - 导入选项
	 * @returns {Promise<string>} 导入后的备份ID
	 */
	async importBackup(importData, format = 'json', options = {}) {
		try {
			let backupData
			
			switch (format.toLowerCase()) {
				case 'json':
					backupData = JSON.parse(importData)
					break
				default:
					throw new Error('不支持的导入格式')
			}
			
			// 验证导入的数据
			const isValid = await this.verifyBackupData(backupData)
			if (!isValid) {
				throw new Error('导入的备份数据格式无效')
			}
			
			// 创建新的备份项
			const backupItem = new BackupItem({
				name: options.name || `导入备份_${new Date().toLocaleString()}`,
				type: BACKUP_TYPES.MANUAL,
				dataTypes: Object.keys(backupData.data || {}),
				size: JSON.stringify(backupData).length
			})
			
			// 保存备份数据
			await this.saveLocalBackupData(backupItem.id, backupData)
			
			// 添加到备份列表
			this.backups.push(backupItem)
			await this.saveBackups()
			
			logInfo('备份导入成功', { backupId: backupItem.id, name: backupItem.name })
			return backupItem.id
		} catch (error) {
			logError('导入备份失败', { error: error.message })
			throw error
		}
	}
	
	/**
	 * 销毁管理器
	 * @returns {Promise<void>}
	 */
	async destroy() {
		try {
			// 清除自动备份定时器
			if (this.autoBackupTimer) {
				clearInterval(this.autoBackupTimer)
				this.autoBackupTimer = null
			}
			
			// 移除事件监听器
			this.listeners.clear()
			
			// 保存当前状态
			await this.saveConfig()
			await this.saveBackups()
			
			logInfo('备份管理器已销毁')
		} catch (error) {
			logError('销毁备份管理器失败', { error: error.message })
		}
	}
}

// 创建全局实例
const backupManager = new BackupManager()

// 导出便捷函数
export const createBackup = (name, dataTypes, options) => 
	backupManager.createBackup(name, dataTypes, options)

export const restoreBackup = (backupId, options) => 
	backupManager.restoreBackup(backupId, options)

export const syncBackup = (backupId) => 
	backupManager.syncBackup(backupId)

export const deleteBackup = (backupId) => 
	backupManager.deleteBackup(backupId)

export const listBackups = () => 
	backupManager.listBackups()

export const getBackupInfo = (backupId) => 
	backupManager.getBackupInfo(backupId)

export const cleanupExpiredBackups = () => 
	backupManager.cleanupExpiredBackups()

export const exportBackup = (backupId, format) => 
	backupManager.exportBackup(backupId, format)

export const importBackup = (importData, format, options) => 
	backupManager.importBackup(importData, format, options)

export const getBackupStats = () => 
	backupManager.getStats()

export const resetBackupStats = () => 
	backupManager.resetStats()

export const updateBackupConfig = (config) => 
	backupManager.updateConfig(config)

export const getBackupConfig = () => 
	backupManager.getConfig()

export const onBackupEvent = (event, callback) => 
	backupManager.on(event, callback)

export const offBackupEvent = (event, callback) => 
	backupManager.off(event, callback)

// 导出类和枚举
export {
	BackupManager,
	BackupItem,
	BACKUP_STATUS,
	BACKUP_TYPES,
	STORAGE_TYPES,
	DATA_TYPES,
	CONFLICT_RESOLUTION
}

// 导出默认实例
export default backupManager